package sword.T20;

/**
 * @File Info: leetcode -- <Solution>
 * @Author: 18362
 * @Create: 2022-03-27 23:00:20 星期日
 */

class Solution {

    private int pos = 0;
    private boolean sign = false;

    public boolean isNumber(String s) {
        s = s.trim();
        if (s.length() == 0)
            return false;
        if (s.charAt(0) == '.') {
            pos++;
            if (!scanUnsignedInt(s))
                return false;
            if (pos == s.length())
                return true;
        } else {
            if (!scanInteger(s) && !sign)
                return false;
            if (pos == s.length())
                return true;
            if (s.charAt(pos) == '.')
                pos++;
            boolean f = scanUnsignedInt(s);
            if (sign && !f)
                return false;
            if (pos == s.length())
                return true;
        }
        if (s.charAt(pos) != 'e' && s.charAt(pos) != 'E')
            return false;
        pos++;
        if (!scanInteger(s))
            return false;
        return pos == s.length();
    }

    private boolean scanInteger(String s) {
        if (pos >= s.length())
            return false;
        int t = pos;
        boolean flag = false;
        if (s.charAt(pos) == '+' || s.charAt(pos) == '-') {
            flag = true;
            pos++;
        }
        boolean res = scanUnsignedInt(s);
        if (flag && t+1 == pos)
            sign = true;
        return res;
    }

    private boolean scanUnsignedInt(String s) {
        int t = pos;
        while(pos < s.length() && s.charAt(pos) >= '0' && s.charAt(pos) <= '9')
            pos++;
        return t != pos;
    }
}